package com.lincoln.gateway.zuul;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * http请求转发
 *
 * @author lincoln
 */
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
    @Autowired
    ZuulProperties zuulProperties;
    @Autowired
    ServerProperties server;

    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }

    @Bean
    public MyRouteLocator routeLocator() {
        MyRouteLocator routeLocator = new MyRouteLocator(this.server.getServlet().getContextPath(), this.zuulProperties);
        return routeLocator;
    }

    public static String add(String site, String path, String url, Boolean stripPrefix) {
        if (site != null && path != null && url != null && !"".equals(site) && !"".equals(path) && !"".equals(url) && stripPrefix != null) {
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            zuulRoute.setId(path);
            zuulRoute.setPath(path);
            zuulRoute.setUrl(url);
            zuulRoute.setStripPrefix(stripPrefix);
            Map<String, ZuulProperties.ZuulRoute> map = new LinkedHashMap<>();
            map.put(zuulRoute.getPath(), zuulRoute);
            if (MyRouteLocator.maps.get(site) == null) {
                MyRouteLocator.maps.put(site, new ConcurrentHashMap<>(0));
            }
            MyRouteLocator.maps.get(site).putAll(map);
            return "大概成功了";
        } else {
            return "参数有问题:" + "-site:" + site + "-path:" + path + "-url:" + url + "-stripPrefix:" + stripPrefix + "";
        }
    }

    public static String delete(String site, String path) {
        if (site != null && path != null && !"".equals(site) && !"".equals(path)) {
            if (MyRouteLocator.maps.get(site) == null || MyRouteLocator.maps.get(site).size() <= 0) {
                return "没这个site或者是空的";
            }
            if (MyRouteLocator.maps.get(site).get(path) == null) {
                return "没这个path";
            }
            MyRouteLocator.maps.get(site).remove(path);
            return "大概成功了";
        } else {
            return "参数有问题:" + "-site:" + site + "-path:" + path + "";
        }
    }
}

